package com.faf.ui;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.faf.bean.Food;
import com.faf.service.FoodService;
import com.faf.service.impl.FoodServiceImpl;

import net.sf.json.JSONObject;

@WebServlet("/AddNewFoodManagement")
public class AddNewFoodManagement extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddNewFoodManagement() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		Food food = new Food();
		String foodName = null, foodPrice = null, foodType = null, foodDescribe = null, foodPhoto = null,
				foodPhoto1 = null, storeId = null;

		String picpath = null;
		boolean ismultipart = ServletFileUpload.isMultipartContent(request);
		if (ismultipart) {
			try {
				FileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				List<FileItem> items = upload.parseRequest(request);
				for (FileItem fileItem : items) {
					if (fileItem.isFormField()) {
						String name = fileItem.getFieldName();
						String value = fileItem.getString();
						if ("storeId".equals(name)) {
							storeId = new String(value.getBytes("iso-8859-1"), "utf-8");
							food.setStoreId(Integer.parseInt(storeId));
						} else if ("foodName".equals(name)) {
							foodName = new String(value.getBytes("iso-8859-1"), "utf-8");
							food.setFoodName(foodName);
						} else if ("foodPrice".equals(name)) {
							foodPrice = new String(value.getBytes("iso-8859-1"), "utf-8");
							food.setFoodPrice(Double.parseDouble(foodPrice));
						} else if ("foodType".equals(name)) {
							foodType = new String(value.getBytes("iso-8859-1"), "utf-8");
							food.setFoodType(foodType);
						} else if ("foodDescribe".equals(name)) {
							foodDescribe = new String(value.getBytes("iso-8859-1"), "utf-8");
							food.setFoodDescribe(foodDescribe);
						} else if ("foodPhoto1".equals(name)) {
							foodPhoto1 = new String(value.getBytes("iso-8859-1"), "utf-8");
							food.setFoodPhoto(foodPhoto1);
						}
					} else {
						String url = getServletContext().getRealPath("/") + "Image/goods/";
						System.out.println(url);
						Date date = new Date();
						SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
						String fileName = "/" + formatter.format(date) + ".jpg";// 用日期当作名字
						File file = new File(url);
						if (!file.exists()) {
							file.mkdirs();
						}
						File savefile = new File(file, fileName);
						System.out.println(savefile);// 路径
						System.out.println(savefile.getName());// 名字
						foodPhoto = "Image/goods/" + savefile.getName();
						System.out.println(foodPhoto);
						if (fileItem.getSize() > 0) {
							InputStream in = fileItem.getInputStream();
							OutputStream os = new FileOutputStream(savefile);
							int len;
							byte[] b = new byte[1024];
							while ((len = in.read(b)) != -1) {
								os.write(b, 0, len);
							}
							food.setFoodPhoto(foodPhoto);
							os.close();
							in.close();
						} else {
							food.setFoodPhoto(foodPhoto1);
						}
					}
				}
				FoodService foodService = new FoodServiceImpl();
				foodService.addNewFood(food);
				JSONObject dataPool = new JSONObject();
				dataPool.put("result", 1);
				response.getWriter().print(dataPool);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		/*
		 * String title=request.getParameter("title"); String
		 * price=request.getParameter("prices"); String img
		 * =request.getParameter("file"); String count=request.getParameter("counts");
		 * File file=new File(img); String
		 * pathpic=getServletContext().getRealPath("/")+"image/"+file.getName();
		 * System.out.println(pathpic); File file2=new File(pathpic);
		 * if(!file2.exists()) file2.createNewFile(); FileInputStream fis=new
		 * FileInputStream(file); FileOutputStream fos=new FileOutputStream(file2); int
		 * len; byte[] b=new byte[1024]; while((len=fis.read(b))!=-1){ fos.write(b, 0,
		 * len); } fos.close(); fis.close();
		 * System.out.println(getServletContext().getRealPath("/")+"==="+file.getName())
		 * ; DCai d=new DCai(); d.setCount(Integer.parseInt(count));
		 * d.setPic("image/"+file.getName());
		 * d.setPrice(Double.parseDouble(price.trim())); d.setTitle(title); DcaiDao
		 * dao=new DcaiDao(); DCai d=new DCai(); d.setCount(Integer.parseInt(count));
		 * d.setPic(picpath); d.setPrice(Double.parseDouble(price.trim()));
		 * d.setTitle(title); int result=dao.insert(d); if(result>0){
		 * 
		 * response.sendRedirect("../welcome.jsp"); }else{
		 * response.sendRedirect("../user_modify.jsp"); }
		 */
	}

}
